package com.sunnada.demo.controller;

import com.sunnada.demo.bean.User;
import com.sunnada.demo.log.annotation.LogRecord;
import com.sunnada.demo.service.UserService;
import com.sunnada.demo.shiro.MyShiroRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: mybatisproject2
 * @BelongsPackage: com.sunnada.demo.controller
 * @Author: 李瑞益
 * @CreateTime: 2018-10-10 16:29
 * @Description: 登录控制
 */
@Controller
@RequestMapping("/shiro")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MyShiroRealm myShiroRealm;

    @RequestMapping("/info")
    @ResponseBody
    public Map getMap(){
        Map map = new HashMap();
        map.put("name", "chen");
        map.put("age", "22");
        map.put("tel", "13682452210");
        return map;
    }

    @RequestMapping("/login")
    public String loginPager(){
        return "login";
    }

    @LogRecord("登录操作")
    @RequestMapping("/loginDeal")
    public String login(HttpServletRequest request, Map<String, Object> map) throws Exception{
        try {
            System.out.println("HomeController.login()");
            //用户信息认证
           Subject subject = SecurityUtils.getSubject();
           String name = request.getParameter("name");
           String password = request.getParameter("password");

            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(name,password);
            //信息认证
            subject.login(usernamePasswordToken);

            User user = (User)subject.getPrincipal();

            map.put("user",user);

//            throw new Exception("自定义错误，测试日志是否可用，");

            return "redirect:index";
        } catch (AuthenticationException e) {
            map.put("msg", "账号不存在a");
            System.out.println("账号不存在a"+e.getMessage());

        }

        return "/login";
    }
    @RequestMapping("/index")
    public String index(){
        return  "index";
    }

    @RequestMapping("/addUser")
    public String addShow(){ return "addUser";
    }

    @RequestMapping("/addUserDeal")
    public String addUser(User user, Model model){
        model.addAttribute("status",userService.insert(user) > 0?true:false);
        return "addUser";
    }
}
